package org.lib.mysqlhello.security.self;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.lib.mysqlhello.common.ResultVO;
import org.lib.mysqlhello.security.self.pojo.AddAppUserDTO;
import org.lib.mysqlhello.security.self.pojo.AppUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

/**
 * AppUser接口
 * 添加、删除、修改、查询等
 * @author ben
 * @date 2021-09-05 10:05:40 CST
 */
@RestController
@RequestMapping(value="/security/appuser")
@Slf4j
public class AppUserController {

	@Autowired
	private AppUserDAO appUserDao;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	/**
	 * 转换旧的明文密码
	 * 然后改库
	 * @author ben
	 * @date 2021-09-07 08:25:51 CST
	 * @param password
	 * @return
	 */
	@GetMapping(value="/encode")
	public String encode(@RequestParam String password) {
		log.info("passwordEncoder={}", passwordEncoder);
		return passwordEncoder.encode(password);
	}
	
	@GetMapping(value="/get")
	public AppUserVO get(@RequestParam Long id) {
		AppUser user = appUserDao.findById(id).orElse(null);
		
		AppUserVO vo = this.fillWithAppUser(user);
		if (vo == null) {
			log.warn("没有找到用户：id={}", id);
		}
		return vo;
	}
	
	@GetMapping(value="/getByUsername")
	public AppUserVO getByUsername(@RequestParam String username) {
		AppUser user = appUserDao.findByUsername(username);
		AppUserVO vo = this.fillWithAppUser(user);
		if (vo == null) {
			log.warn("没有找到用户：username={}", username);
		}
		return vo;
	}
	
	/**
	 * 实体类对象转VO对象
	 * @author ben
	 * @date 2021-09-05 16:41:28 CST
	 * @param user
	 * @return
	 */
	private AppUserVO fillWithAppUser(AppUser user) {
		if (user == null) {
			return null;
		}
		
		AppUserVO vo = new AppUserVO();
		
		// 拷贝数据
		vo.setId(user.getId());
		vo.setUsername(user.getUsername());
		vo.setRoles(user.getRoles().replace(AppUser.ROLES_PREFIX, ""));
		vo.setEnabled(user.getEnabled());
		vo.setExpiration(user.getExpiration());
		vo.setCreateTime(user.getCreateTime());
		vo.setUpdateTime(user.getUpdateTime());
		
		return vo;
	}

	/**
	 * 添加用户
	 * @author ben
	 * @date 2021-09-05 15:35:26 CST
	 * @param dto
	 * @return 成功返回新用户ID
	 */
	@PostMapping(value="/add")
	public ResultVO<Long> addAppUser(@RequestBody AddAppUserDTO dto) {
		AppUser user = new AppUser();
		user.setUsername(dto.getUsername());
		// 1、明文存储：不安全
//		user.setPassword(dto.getPassword());
		// 2、使用PasswordEncoder-BCryptPasswordEncoder加密了存储
		user.setPassword(passwordEncoder.encode(dto.getPassword()));
		
		List<String> roles = dto.getRoleList();
		String rolesStr = "";
		if (roles != null && !roles.isEmpty()) {
			// 角色名添加前缀
			List<String> rolesNew = new ArrayList<>();
			roles.forEach(item->{
				rolesNew.add(AppUser.ROLES_PREFIX + item);
			});
			// 使用添加了前缀的角色列表
			rolesStr = String.join(AppUser.ROLES_SEP, rolesNew);
		}
		user.setRoles(rolesStr);
		
		user.setEnabled(dto.getEnabled() == null ? true : dto.getEnabled());
		
		Date exp = dto.getExpirationDate();
		if (Objects.nonNull(exp)) {
			user.setExpiration(exp.getTime());
		}
		
		AppUser savedUser = appUserDao.save(user);
		log.info("新增用户：id={}, username={}", savedUser.getId(), savedUser.getUsername());
		if (savedUser.getId() != null) {
			return ResultVO.getSuccess(savedUser.getId());
		} else {
			return ResultVO.getFailed(HttpStatus.INTERNAL_SERVER_ERROR.value(), "新增用户失败", null);
		}
	}
	
}
